package priv.blackbibo.application.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.VectorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import priv.blackbibo.application.R;

public class CameraActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "CameraActivity";
    private GridLayout content = null;
    private View body = null;
    private Handler handler = new Handler();
    private int requireWidth = 0;

    public int getThisWidth(){
        return this.getResources().getDisplayMetrics().widthPixels;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        body = findViewById(R.id.body);
        content = findViewById(R.id.content);
        int width = getThisWidth();
        requireWidth = width / 3;

        View camera = LinearLayout.inflate(this, R.layout.take_photo_btn, content);

        ImageView imageView = camera.findViewById(R.id.img);
        imageView.getLayoutParams().width = requireWidth;
        imageView.getLayoutParams().height = requireWidth;
        imageView.setOnClickListener(this);
        BackwardShowThread backwardShowThread = new BackwardShowThread();
        backwardShowThread.start();
    }

    public void takePicture(){
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    @Override
    public void onClick(View v) {
        dispatchTakePictureIntent();
    }

    static final int REQUEST_IMAGE_CAPTURE = 1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            scaleAndPutIntoContent(currentPhotoPath);
            galleryAddPic();
        }
    }

    String currentPhotoPath;

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    static final int REQUEST_TAKE_PHOTO = 1;

    /**
     * 将照片放到存储里
     */
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                ex.printStackTrace();
                return;
            }
            // Continue only if the File was successfully created
            if (photoFile != null && photoFile.exists()) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "priv.blackbibo.application.activity.CameraActivity",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(currentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }



    public void showAllPics(){
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (storageDir != null && storageDir.isDirectory()) {
            File[] files = storageDir.listFiles();
            for (File f : files) {
                if (f.length() <=0){
                    continue;
                }

                String absolutePath = f.getAbsolutePath();
                scaleAndPutIntoContent(absolutePath);
            }
        }
    }

    private void scaleAndPutIntoContent(String absolutePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(absolutePath,options);

        int outWidth = options.outWidth;
        int outHeight = options.outHeight;

        int sampleSize = Math.min(outWidth / requireWidth, outHeight / requireWidth);
        options.inSampleSize = sampleSize;

        options.inJustDecodeBounds = false;


        Bitmap bitmap = BitmapFactory.decodeFile(absolutePath, options);

        int minSize = Math.min(options.outWidth, options.outHeight);

        int shiftWidth = (options.outWidth - requireWidth) / 2;
        int shiftHeight = (options.outHeight - requireWidth) / 2;

        Bitmap newBitMap = Bitmap.createBitmap(requireWidth, requireWidth, Bitmap.Config.ARGB_8888);

        int[] pixels = new int[requireWidth * requireWidth];
        bitmap.getPixels(pixels,0,requireWidth,shiftWidth,shiftHeight,requireWidth,requireWidth);
        newBitMap.setPixels(pixels, 0, requireWidth, 0, 0, requireWidth, requireWidth);

        View view = ImageView.inflate(this, R.layout.scale_image_view, null);

        ImageView imageView = view.findViewById(R.id.img);
        imageView.setImageBitmap(newBitMap);

        TextView path = view.findViewById(R.id.path);
        path.setText(absolutePath);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView pathText = v.findViewById(R.id.path);
                String path = pathText.getText().toString();
                fullScreen(path);
            }
        });

        handler.post(()->{
            content.addView(view);
        });
    }

    public void fullScreen(String path){
        Intent intent = new Intent(this, FuallScreenPhotoActivity.class);
        intent.putExtra("path", path);
        startActivity(intent);
    }

    class BackwardShowThread extends Thread {
        @Override
        public void run() {
            showAllPics();
        }
    }
}
